<template>
  <div class="chart-container">
    <div
      ref="chartRef"
      :style="{ width: chartWidth, height: chartHeight }"
    ></div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, onUnmounted } from "vue";
import * as echarts from "echarts";

// 定义组件接收的props
const props = defineProps({
  // 主要数据数组
  cellItems: {
    type: Array,
    required: true,
    default: () => [],
  },
  // Y轴最大值
  maxValue: {
    type: Number,
    default: 11,
  },
  // 图表宽度
  chartWidth: {
    type: [String, Number],
    default: "100%",
  },
  chartHeight: {
    type: [String, Number],
    default: "200px",
  },
});

// 图表容器引用
const chartRef = ref(null);
// 图表实例
let chartInstance = null;

// 初始化图表
const initChart = () => {
  // 销毁已有实例
  if (chartInstance) {
    chartInstance.dispose();
  }

  // 创建新实例
  chartInstance = echarts.init(chartRef.value);

  // 设置图表配置
  updateChart();
};

// 更新图表数据和配置
const updateChart = () => {
  if (!chartInstance || !props.cellItems.length) return;

  // 提取X轴和Y轴数据
  const xAxisData = props.cellItems.map((item) => item.shortTime);
  const seriesData = props.cellItems.map((item) => item.value ?? 0); // 处理null值

  // 图表配置项
  const option = {
    // 背景色
    backgroundColor: "transparent",

    // 提示框配置
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
      backgroundColor: "#333",
      borderColor: "#666",
      borderWidth: 1,
      padding: 12,
      textStyle: {
        color: "#CFD3DC",
      },
      formatter: function (params) {
        const item = props.cellItems[params[0].dataIndex];
        // const date = new Date(item.day).toLocaleDateString();
        // return `${date} ${item.time}<br/>数值: ${item.value ?? '无数据'}`;
        return `${item.shortDate} ${item.shortTime}<br/>数值: ${
          item.value ?? "无数据"
        }`;
      },
    },

    // 网格配置
    grid: {
      left: "8px",
      right: "8px",
      bottom: "8px",
      top: "24px",
      containLabel: true,
    },

    // X轴配置
    xAxis: {
      type: "category",
      data: xAxisData,
      axisLine: {
        lineStyle: {
          color: "#ccc",
        },
      },
      axisLabel: {
        color: "#888",
        interval: 0,
        rotate: 45,
        fontSize: 11,
      },
      axisTick: {
        alignWithLabel: true,
      },
      splitLine: {
        show: true,
        interval: 0,
        lineStyle: {
          color: "#8884",
          type: "dotted",
        },
      },
    },

    // Y轴配置
    yAxis: {
      type: "value",
      max: props.maxValue || undefined,
      axisLine: {
        show: false,
      },
      axisLabel: {
        color: "#888",
        fontSize: 12,
        formatter: "{value}",
      },
      splitLine: {
        show: true,
        interval: 0,
        lineStyle: {
          color: "#8884",
          type: "dotted",
        },
      },
      boundaryGap: [0, "10%"],
    },

    // 系列数据配置
    series: [
      {
        name: "数值",
        type: "bar",
        data: seriesData,
        // 柱形样式
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "#4096ff" },
            { offset: 1, color: "#6aa8ff" },
          ]),
          borderRadius: [4, 4, 0, 0],
        },
        // 柱形宽度
        barWidth: "60%",
        // 高亮效果
        emphasis: {
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: "#3685ff" },
              { offset: 1, color: "#5c9dff" },
            ]),
          },
        },
        // 数据标签
        label: {
          show: true,
          position: "top",
          color: "#888",
          fontSize: 12,
          fontWeight: "bold",
          formatter: function (params) {
            return params.value || "-";
          },
        },
      },
    ],
  };

  // 设置配置项
  chartInstance.setOption(option);
};

// 监听窗口大小变化，调整图表
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};

// 组件挂载时初始化图表
onMounted(() => {
  initChart();
  window.addEventListener("resize", handleResize);
});

// 监听数据变化，更新图表
watch(
  () => [props.cellItems, props.maxValue, props.chartWidth],
  () => {
    updateChart();
    handleResize();
  },
  { deep: true }
);

// 组件卸载时清理
onUnmounted(() => {
  window.removeEventListener("resize", handleResize);
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
});
</script>

<style scoped>
.chart-container {
  position: relative;
  overflow: hidden;
}
</style>
